﻿<!DOCTYPE html>
@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Overall stats";
    
    string dateAndScore = string.Empty;
    int gameId = Request["gameId"].AsInt();
    string opponent = string.Empty;
    var db = Database.Open("ICRams");
    string whereClause = string.Empty;
    int playerId = Request["player"].AsInt();
    string playerName = string.Empty;
    string warning = "Data for this player does not exist for this game yet.";
  
    if(IsPost)
    {
        if(gameId > 0 && playerId > 0){
            
            /////////////////////////////////////////// Hitting Section //////////////////////////////////////////////////////
            
            var homeRuns = Request["homeRuns"].AsInt();
            var triples = Request["triples"].AsInt();
            var doubles = Request["doubles"].AsInt();
            var singles = Request["singles"].AsInt();
            var walks = Request["walks"].AsInt();
            var groundOuts = Request["groundOuts"].AsInt();
            var flyOuts = Request["flyOuts"].AsInt();
            var reachOnError = Request["reachOnError"].AsInt();
            var hitByPitch = Request["hitByPitch"].AsInt();
            var sacrifices = Request["sacrifices"].AsInt();
            var stolenBases = Request["stolenBases"].AsInt();
            var runs = Request["runs"].AsInt();
            var rbi = Request["rbi"].AsInt();
            var strikeoutsSwinging = Request["strikeoutsSwinging"].AsInt();
            var strikeoutsLooking = Request["strikeoutsLooking"].AsInt();
            
            //If a row already exists for this player for this game, update it, otherwise enter a new row.
            var existingRows = db.Query(@"SELECT * FROM HittingStats WHERE GameId = " + gameId + " AND playerId = " + playerId);
            if(existingRows == null || existingRows.Count() == 0){            
                var SQLINSERT = @"INSERT INTO HittingStats(PlayerId, GameId, HomeRuns, Triples, Doubles, Singles, Walks, GroundOuts, ReachOnError, FlyOuts, Sacrifices, HitByPitch, RBI, StolenBases, Runs, StrikeoutsSwinging, StrikeoutsLooking)
                VALUES(@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16)";
                db.Execute(SQLINSERT, playerId, gameId, homeRuns, triples, doubles, singles, walks, groundOuts, reachOnError,flyOuts, sacrifices, hitByPitch, rbi,  stolenBases, runs, strikeoutsSwinging, strikeoutsLooking);
            }
            else
            {          
                var SQLUPDATE = @"UPDATE HittingStats SET PlayerId=@0, GameId=@1, HomeRuns=@2, Triples=@3, Doubles=@4, Singles=@5, Walks=@6, GroundOuts=@7, ReachOnError=@8, FlyOuts=@9, Sacrifices=@10, HitByPitch=@11, RBI=@12, StolenBases=@13, Runs=@14, StrikeoutsSwinging=@15, StrikeoutsLooking=@16
                WHERE PlayerId = @0 AND GameId = @1";
                db.Execute(SQLUPDATE, playerId, gameId, homeRuns, triples, doubles, singles, walks, groundOuts, reachOnError,flyOuts, sacrifices, hitByPitch, rbi,  stolenBases, runs, strikeoutsSwinging, strikeoutsLooking);
            }
            
            /////////////////////////////////////////// Pitching Section //////////////////////////////////////////////////////
            var homeRunsGivenUp = Request["homeRunsGivenUp"].AsInt();
            var triplesGivenUp = Request["triplesGivenUp"].AsInt();
            var doublesGivenUp = Request["doublesGivenUp"].AsInt();
            var singlesGivenUp = Request["singlesGivenUp"].AsInt();
            var walksGivenUp = Request["walksGivenUp"].AsInt();
            var ks = Request["ks"].AsInt();
            var hitBatter = Request["hitBatter"].AsInt();
            var errors = Request["errors"].AsInt();
            var inningsPitched = Request["inningsPitched"].AsFloat();
            var earnedRuns = Request["earnedRuns"].AsInt();
            var totalRuns = Request["totalRuns"].AsInt();
            var firstPitchStrikes = Request["firstPitchStrikes"].AsInt();
            var battersFaced = Request["battersFaced"].AsInt();
            var strikes = Request["strikes"].AsInt();
            var balls = Request["balls"].AsInt();
            var outs = Request["outs"].AsInt();

            //Don't add a pitching stats row if no pitching stats were entered.
            if(homeRunsGivenUp + triplesGivenUp + doublesGivenUp + singlesGivenUp + 
                    walksGivenUp + ks + hitBatter + errors + inningsPitched + earnedRuns + totalRuns + firstPitchStrikes + battersFaced + strikes + balls > 0)
            {
                //If a row already exists for this player for this game, update it, otherwise enter a new row.
                var existingPitchingRows = db.Query(@"SELECT * FROM PitchingStats WHERE GameId = " + gameId + " AND playerId = " + playerId);
                if(existingPitchingRows == null || existingPitchingRows.Count() == 0){            
                    var SQLINSERT = @"INSERT INTO PitchingStats(PlayerId, GameId, HomeRuns, Triples, Doubles, Singles, Walks, Strikeouts, HitBatter, Error, InningsPitched, EarnedRuns, TotalRuns, FirstPitchStrikes, BattersFaced, Strikes, Balls, FieldOuts)
                    VALUES(@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17)";
                    db.Execute(SQLINSERT, playerId, gameId, homeRunsGivenUp, triplesGivenUp, doublesGivenUp, singlesGivenUp, 
                    walksGivenUp, ks, hitBatter, errors, inningsPitched, earnedRuns, totalRuns, firstPitchStrikes, battersFaced, strikes, balls, outs);
                }
                else
                {          
                    var SQLUPDATE = @"UPDATE PitchingStats SET PlayerId=@0, GameId=@1, HomeRuns=@2, Triples=@3, Doubles=@4, Singles=@5, Walks=@6, Strikeouts=@7, HitBatter=@8, Error=@9, InningsPitched=@10, EarnedRuns=@11, TotalRuns=@12, FirstPitchStrikes=@13, BattersFaced=@14, Strikes=@15, Balls=@16, FieldOuts=@17
                    WHERE PlayerId = @0  AND GameId = @1 ";
                    db.Execute(SQLUPDATE, playerId, gameId, homeRunsGivenUp, triplesGivenUp, doublesGivenUp, singlesGivenUp, walksGivenUp, ks, hitBatter, errors, inningsPitched, earnedRuns, totalRuns, firstPitchStrikes, battersFaced, strikes, balls, outs);
                }
            }
                        
        }
        else{
            ModelState.AddError("GameId", "Either no game id or no player id was sent");
        }
        
    }
    
    if(gameId > 0){    
            
        var games = db.Query(@"SELECT TOP 1 Games.Id, Games.Opponent, Games.OurScore, Games.OpponentScore, Games.GameDate, Games.HomeAway FROM Games WHERE Games.Id = " +  gameId);
        var game = games.FirstOrDefault();
        if(game != null){
            Page.Title = "Enter stats for the game " + game.HomeAway + " " + game.Opponent + " on " + game.GameDate.ToShortDateString();
            dateAndScore = "IC:" + game.OurScore + " - " + game.Opponent + ":" + game.OpponentScore;
            gameId = game.Id;
            opponent = game.Opponent;
        }
        else
        {
            db.Close();
            Response.Write("That game does not exist");
            Response.End();
        }
        
    }
    else
    {
        db.Close();
        Response.Write("No game specified.");
        Response.End();
    }
    
    var players = db.Query(@"SELECT DISTINCT Players.Id, Players.DisplayName, HittingStats.GameId
                                    FROM Players LEFT OUTER JOIN HittingStats ON HittingStats.PlayerId = Players.Id 
                                    AND HittingStats.GameId = " + gameId + @" ORDER BY HittingStats.GameId ASC" );    
}

        <script>
        $(document).ready(function(){
            $("#homeRuns").select();
            $("input").change(function(){
                if(isNaN($(this).val())){
                   // alert($(this).val() + " is not a number");
                    $(this).val("0");
                    $(this).focus();
                    $(this).select();
                }
            });
            $("input").click(function(){
                $(this).select();
            });
            $("form").submit(function(){
                var name = $("#player option:selected").text();
                var currentForm = this;
                return confirm("Enter this data for " + name + "?");
            });
        });
        
        </script>
    @Html.ValidationSummary(excludeFieldErrors: false)
        <fieldset>
            <form action="" method="post">

            <select id="player" name="player">
            @foreach(var player in players){
                warning = (player.gameId == gameId) ? " - His stats already exist for this game AND WILL BE OVERWRITTEN!!!!" : " (No data entered yet for this game)";
            <option value="@player.Id">@player.DisplayName  @warning
            </option>    

            }
            </select>

            @*{ var x = 1; }*@
            
            @* Works just fine *@
            @*{if(x==1) { <span>x is @x</span> } else { <span>x is not @x</span> ;}}*@
            
            @* Fails if not wrapped in html tags:*@
            @*{if(x==1) { <text>x is one</text> } else {<text>x is not one</text>}}   *@
            
            @* Works - will write a string not contained in an html tag. *@
            @*{if(x==1) { @("x is ")@x } else {@("x is not ")@x}}*@
            
                
            <br />
            <div style="float:left;padding-right:50px;">
            <input type="hidden" id="gameId" name="gameId" value="@gameId" />
            <label for="homeRuns">HR</label>
            <input type="text" id="homeRuns"  name="homeRuns" value="0"/>
            <br />
            <label for="triples">3B</label>
            <input type="text" id="triples" name="triples" value="0"/>
            <br />
            <label for="doubles">2B</label>
            <input type="text" id="doubles" name="doubles" value="0"/>
            <br />
            <label for="singles">1B</label>
            <input type="text" id="singles" name="singles" value="0"/>
            <br />
            <label for="walks">BB</label>
            <input type="text" id="walks" name="walks" value="0"/>
            <br />
            <label for="groundOuts">GO</label>
            <input type="text" id="groundOuts" name="groundOuts" value="0"/>
            <br />
            <label for="flyOuts">FO</label>
            <input type="text" id="flyOuts" name="flyOuts" value="0"/>
            <br />
            <label for="reachOnError">Reach On Error</label>
            <input type="text" id="reachOnError" name="reachOnError" value="0"/>
            <br />
            <label for="hitByPitch">HBP</label>
            <input type="text" id="hitByPitch" name="hitByPitch" value="0"/>
            <br />
            <label for="sacrifices">SAC</label>
            <input type="text" id="sacrifices" name="sacrifices" value="0"/>
            <br />
            <label for="stolenBases">SB</label>
            <input type="text" id="stolenBases" name="stolenBases" value="0"/>
            <br />
            <label for="runs">Runs</label>
            <input type="text" id="runs" name="runs" value="0"/>
            <br />
            <label for="rbi">RBI</label>
            <input type="text" id="rbi" name="rbi" value="0"/>
            <br />
            <label for="strikeoutsSwinging">SO(swinging)</label>
            <input type="text" id="strikeoutsSwinging" name="strikeoutsSwinging" value="0"/>
            <br />
            <label for="strikeoutsLooking">SO(looking)</label>
            <input type="text" id="strikeoutsLooking" name="strikeoutsLooking" value="0"/>
            <br />
            <br />
            <br />
            </div>
            <div style="float:left;">
            <h4>(Pitching)</h4>
            <label for="homeRunsGivenUp">HR</label>
            <input type="text" id="homeRunsGivenUp" name="homeRunsGivenUp" value="0"/>
            <br />
            <label for="triplesGivenUp">3B</label>
            <input type="text" id="triplesGivenUp" name="triplesGivenUp" value="0"/>
            <br />
            <label for="doublesGivenUp">2B</label>
            <input type="text" id="doublesGivenUp" name="doublesGivenUp" value="0"/>
            <br />
            <label for="singlesGivenUp">1B</label>
            <input type="text" id="singlesGivenUp" name="singlesGivenUp" value="0"/>
            <br />
            <label for="ks">K</label>
            <input type="text" id="ks" name="ks" value="0"/>
            <br />
            <label for="walksGivenUp">BB</label>
            <input type="text" id="walksGivenUp" name="walksGivenup" value="0"/>
            <br />
            <label for="inningsPitched">IP</label>
            <input type="text" id="inningsPitched" name="inningsPitched" value="0"/>
            <br />
            <label for="balls">B</label>
            <input type="text" id="balls" name="balls" value="0"/>
            </div>
            <div style="top:44px;position:relative;">
                <label for="strikes">S</label>
                <input type="text" id="strikes" name="strikes" value="0"/>
                <br />
                <label for="hitBatter">Hit Batters</label>
                <input type="text" id="hitBatter" name="hitBatter" value="0"/>
                <br />
                <label for="errors">Field Errors</label>
                <input type="text" id="errors" name="errors" value="0"/>
                <br />
                <label for="firstPitchStrikes">First-pitch strikes</label>
                <input type="text" id="firstPitchStrikes" name="firstPitchStrikes" value="0"/>
                <br />
                <label for="earnedRuns">Earned Runs</label>
                <input type="text" id="runsGivenUp" name="earnedRuns" value="0"/>
                <br />
                <label for="totalRuns">Total Runs</label>
                <input type="text" id="totalRuns" name="totalRuns" value="0"/>
                <br />
                <label for="battersFaced">Batters Faced</label>
                <input type="text" id="battersFaced" name="battersFaced" value="0"/>
                <br />
                <label for="outs">Outs (in field)</label>
                <input type="text" id="outs" name="outs" value="0"/>
            <br />
            <br />
            <br />
            <br />
            <input type="submit" style="margin-left:0px;"  id="submitData" value="Insert Stats for the game against @opponent"/>
            </div>
            </form>
        </fieldset>
